package com.pdstudio.carrecom.ui.activity.more;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.lidroid.xutils.http.client.multipart.MultipartEntity;
import com.lidroid.xutils.http.client.multipart.content.ContentBody;
import com.lidroid.xutils.http.client.multipart.content.FileBody;
import com.lidroid.xutils.http.client.multipart.content.StringBody;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.app.UIHelper;
import com.pdstudio.carrecom.ui.view.SelectPicWindow;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.graphics.Bitmap;

/**
 * 修改用户头像
 * 类: ActivityModifierIcon <br>
 * 描述: TODO <br>
 * 作者: xiangzhaoyu  <br>
 * 时间: 2015-6-8 下午2:48:36
 */
public class ActivityModifierIcon extends Activity {
	
	private TextView txtTitle;
	private ImageView ivBack;
	private LinearLayout mModifier;
	private com.pdstudio.carrecom.ui.view.CircleImageView micon;
	private TextView mUser;
	
	private static final int NONE = 0;
	private static final int PHOTO_GRAPH = 1;// 拍照
	private static final int PHOTO_ZOOM = 2; // 缩放
	private static final int PHOTO_RESOULT = 3;// 结果
	private static final String IMAGE_UNSPECIFIED = "image/*";
	//自定义的弹出框类
    SelectPicWindow menuWindow;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_more_modifiericon);

		initTitle();
		InitialView();
	}

	private void initTitle() {
		txtTitle = (TextView) findViewById(R.id.title_text_nav);

		txtTitle.setText("用户图标");

		ivBack = (ImageView) findViewById(R.id.title_back);
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void InitialView() {
		mModifier=(LinearLayout)findViewById(R.id.ll_more_modifiericon);
		mModifier.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//实例化SelectPicPopupWindow
                menuWindow = new SelectPicWindow(ActivityModifierIcon.this, itemsOnClick);
                //显示窗口
                menuWindow.showAtLocation(ActivityModifierIcon.this.findViewById(R.id.ll_more_modifiericon), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
			}});
		
		micon=(com.pdstudio.carrecom.ui.view.CircleImageView)findViewById(R.id.profile_image);
		mUser=(TextView)findViewById(R.id.tv_icon_username);
		mUser.setText(AppContext.getInstance()._userName);
	}
	
	//为弹出窗口实现监听类
    private OnClickListener  itemsOnClick = new OnClickListener(){
 
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
            case R.id.btn_take_photo:
            {
            	Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
						Environment.getExternalStorageDirectory(), "temp.jpg")));
				startActivityForResult(intent, PHOTO_GRAPH);
            }break;
            case R.id.btn_pick_photo:               
            {
            	Intent intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						IMAGE_UNSPECIFIED);
				startActivityForResult(intent, PHOTO_ZOOM);
            }break;
            default:
                break;
            }
             
                 
        }
         
    };
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == NONE)
			return;
		// 拍照
		if (requestCode == PHOTO_GRAPH) {
			// 设置文件保存路径
			File picture = new File(Environment.getExternalStorageDirectory()
					+ "/temp.jpg");
			startPhotoZoom(Uri.fromFile(picture));
		}

		if (data == null)
			return;

		// 读取相册缩放图片
		if (requestCode == PHOTO_ZOOM) {
			startPhotoZoom(data.getData());
		}
		// 处理结果
		if (requestCode == PHOTO_RESOULT) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)压缩文件
				// 此处可以把Bitmap保存到sd卡中，具体请看：http://www.cnblogs.com/linjiqin/archive/2011/12/28/2304940.html
				micon.setImageBitmap(photo); // 把图片显示在ImageView控件上
				UploadImg(stream);
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}
    
    /**
	 * 收缩图片
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 500);
		intent.putExtra("outputY", 500);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTO_RESOULT);
	}

	/**
	 * 上传图片
	 * 方法: UploadImg <br>
	 * 描述: TODO <br>
	 * 作者: xiangzhaoyu  <br>
	 * 时间: 2015-6-26 下午1:55:53
	 */
	private void UploadImg(ByteArrayOutputStream stream) {
		try {
			URL url = new URL(ServiceHelper.UploadImg);
			HttpClient httpclient = new DefaultHttpClient();
			// 设置通信协议版本
			httpclient.getParams().setParameter(
					CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

			HttpPost httppost = new HttpPost(ServiceHelper.UploadImg);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			File file = new File(Environment.getExternalStorageDirectory()
					,"temp.jpg");
			try {
				BufferedOutputStream bos = null;
				FileOutputStream fos = new FileOutputStream(file);
				bos = new BufferedOutputStream(fos);
				bos.write(stream.toByteArray());
				bos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			/* pb长度 */
			// pb.setMax((int) file.length());

			MultipartEntity mpEntity = new MultipartEntity(); // 文件传输
			ContentBody cbFile = new FileBody(file);
			mpEntity.addPart("imgFile", cbFile); // <input type="file"
													// name="userfile" /> 对应的
			ContentBody os = new StringBody("android",Charset.forName(HTTP.UTF_8));
			ContentBody id = new StringBody(AppContext.getInstance()._userId+"",Charset.forName(HTTP.UTF_8));
			
			mpEntity.addPart("os", os);
			mpEntity.addPart("id", id);

			httppost.setEntity(mpEntity);
			System.out
					.println("executing request " + httppost.getRequestLine());

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			System.out.println(response.getStatusLine());// 通信Ok
			String json = "";
			String path = "";
			if (resEntity != null) {
				// System.out.println(EntityUtils.toString(resEntity,"utf-8"));
				json = EntityUtils.toString(resEntity, "utf-8");
				JSONObject p = null;
				try {
					p = new JSONObject(json);
					// path=(String) p.get("path");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (resEntity != null) {
				resEntity.consumeContent();
			}

			httpclient.getConnectionManager().shutdown();
			//mHandler.sendEmptyMessage(1);
		} catch (Exception e) {
			UIHelper.ToastMessage(this, "图像上传压缩出现错误");
		}
	}
	
}
